import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
    {
        path: '/login',
        name: 'Login',
        component: () => import('@/views/login/Login'),
        meta: { title: '登录', noAuth: true }
    },
    {
        path: '/register',
        name: 'Register',
        component: () => import('@/views/login/Register'),
        meta: { title: '注册', noAuth: true }
    },
    {
        path: '/',
        component: () => import('@/views/Layout'),
        redirect: '/user',
        children: [
            {
                path: 'user',
                name: 'User',
                component: () => import('@/views/user/UserList'),
                meta: { title: '用户管理' }
            },
            {
                path: 'department',
                name: 'Department',
                component: () => import('@/views/department/DepartmentList'),
                meta: { title: '部门管理' }
            }
        ]
    },
    {
        path: '/404',
        component: () => import('@/views/error/404'),
        hidden: true,
        meta: { noAuth: true }
    },
    {
        path: '*',
        redirect: '/404',
        hidden: true
    }
]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
    // 设置页面标题
    document.title = to.meta.title ? `${to.meta.title} - 用户部门管理系统` : '用户部门管理系统'

    // 判断该路由是否需要登录权限
    if (!to.meta.noAuth) {
        const token = localStorage.getItem('token')
        if (token) {
            next()
        } else {
            // 没有token，重定向到登录页
            next({
                path: '/login',
                query: { redirect: to.fullPath } // 将要跳转的路由path作为参数，登录成功后跳转到该路由
            })
        }
    } else {
        // 不需要登录权限的路由直接放行
        next()
    }
})

export default router 